#include <QCoreApplication>
#include <QTcpSocket>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
#include <QTimer>
#include <QCryptographicHash>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QTcpSocket socket;

    qDebug() << "[Client] Connecting to server...";
    socket.connectToHost("127.0.0.1", 8888);

    if (socket.waitForConnected(3000)) {
        qDebug() << "[Client] Connected!";

        // ==================== 开始修改 ====================

        // 1. 构建登录请求的 JSON 对象
        QJsonObject loginRequest;
        loginRequest["type"] = "login_request"; // <--- 修改 type
        loginRequest["username"] = "testuser_from_qt";

        // 2. 计算密码 "password123" 的 MD5 哈希值
        QString password = "password123";
        QByteArray passwordHash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Md5);
        loginRequest["password"] = QString(passwordHash.toHex()); // 发送哈希值的十六进制字符串表示

        // ==================== 修改结束 ====================

        // 3. 将 JSON 对象转换为 QByteArray
        QByteArray jsonData = QJsonDocument(loginRequest).toJson(QJsonDocument::Compact);

        // 4. 按照我们的协议封包：[长度-内容]
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_6_0);
        out << (qint32)jsonData.size();
        out.writeRawData(jsonData.constData(), jsonData.size());

        // 5. 发送封包后的数据
        qDebug() << "[Client] Sending login request..."; // (可选) 修改日志
        socket.write(block);
        socket.flush();

        // 等待1秒，给服务器足够的时间处理和打印日志
        if (socket.waitForReadyRead(1000))
        {
            qDebug() << "[Client] Received response:" << socket.readAll();
        }

        // 6. 断开连接
        qDebug() << "[Client] Disconnecting...";
        socket.disconnectFromHost();
        if (socket.state() == QAbstractSocket::UnconnectedState || socket.waitForDisconnected(1000))
        {
            qDebug() << "[Client] Disconnected successfully.";
        }

    }
    else
    {
        qDebug() << "[Client] Connection failed:" << socket.errorString();
    }

    // 稍微等待一下，确保所有日志都打印出来，然后退出
    QTimer::singleShot(1500, &a, &QCoreApplication::quit);




    return a.exec();
}
